#define _CRT_SECURE_NO_WARNINGS 1

#include "List.h"

ListNode* ListInit()
{
	ListNode* phead = (ListNode*)malloc(sizeof(ListNode));
	phead->next = phead;
	phead->prev = phead;
	return phead;
}
void ListPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	//ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	//ListNode* tail=phead->prev;
	//newnode->val = x;
	////phead       tail      newnode
	//tail->next = newnode;
	//newnode->prev = tail;
	//newnode->next = phead;
	//phead->prev = newnode;
	ListInsert(phead, x);
}

void ListPrint(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushFront(ListNode* phead,LTDataType x)
{
	assert(phead);
	////phead  newnode  next 
	//ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	//newnode->val = x;
	//ListNode* next = phead->next;

	//phead->next = newnode;
	//newnode->prev = phead;

	//newnode->next = next;
	//next->prev = newnode;
	ListInsert(phead->next, x);
}

void ListPopBack(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
//	//phead     tailprev   tail
//	ListNode* tail = phead->prev;
//	ListNode* tailprev = tail->prev;
//	free(tail);
//	tail = NULL;
//	tailprev->next = phead;
//	phead->prev = tailprev;
	ListErase(phead->prev);
}

void ListPopFront(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	//ListNode* cur = phead->next;
	//ListNode* next = cur->next;
	////phead   cur   next  
	//free(cur);
	//cur = NULL;
	//phead->next = next;
	//next->prev = phead;
	ListErase(phead->next);
}

ListNode* ListFind(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur!=phead)
	{
		if (cur->val == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListDestroy(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	//phead cur next 
	while (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(cur);
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* posprev = pos->prev;
	//posprev  pos  
	//posprev  newnode pos 
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	newnode->val = x;
	posprev->next = newnode;
	newnode->prev = posprev;
	 
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	// posprev  pos  posnext
	ListNode* posprev = pos->prev;
	ListNode* posnext = pos->next;
	free(pos);
	pos=NULL;
	posprev->next = posnext;
	posnext->prev = posprev;
}